var key = "48b9386188e47d9cbfa6621ee295b623";
var serverUrl = "https://www.ymqvip.com/api/";
var md5 = require("md5.js");
var util = require('../utils/util.js')

function getSign(para) {
  para.timestamp = new Date().getTime();
  var sdic = Object.keys(para).sort();
  var str = "";
  for (var ki in sdic) {
    if (typeof para[sdic[ki]] == "object")
      continue;
    if (para[sdic[ki]] == null)
      continue;
    str += sdic[ki] + encodeURIComponent(para[sdic[ki]]);
  }
  // console.log(str+key);
  var sign = md5.hex_md5(str + key);
  para["sign"] = sign;
  return para;
}

function wxRequest(data, cb) {
  wx.request({
    url: serverUrl + data['url'],
    data: getSign(data),
    method: "POST",
    header: {
      'content-type': 'application/json'
    },
    success: function(res) {
      util.hideToast()
      // console.log('网络请求结果', res)
      if (res.data.code != 0) {
        util.showModal(res.data.message);
      } else
        cb(res.data.data);
    },
    fail: function(err) {
      console.log('网络请求失败', data, err)
      cb({
        code: 1,
        message: '网络请求失败，请重试'
      });
    }
  })
}

function post(data, cb) {
  var that = getApp()

  data["token"] = wx.getStorageSync('token') || "";

  //没有token 调接口 先调登录（除了登录接口以外）
  if (data["token"] == "" && data['url'] != "weixin/login") {
    var userInfo = wx.getStorageSync('userInfo'); 
    if (userInfo) {
      console.log('已存在用户信息');
      typeof cb == "function" && cb(userInfo)

    } else {
      console.log('不存在用户信息，跳转登录');
      that.getUserInfo(() => {
        data["token"] = wx.getStorageSync('token') || "";
        wxRequest(data, cb)
      })
    }
  } else {
    //直接调接口
    util.showBusy('努力加载中…')
    wxRequest(data, cb)
  }
}

module.exports = {
  post,
  getSign
}